import {
	createStore,
	useStore
} from "vuex";
import createPersistedState from "vuex-persistedstate";
import {
	loginApi,
	getInfo
} from "/api/index";
const {
	dispatch,
	state,
	commit
} = useStore();
const store = createStore({
	state: {
		system: {}, //系统信息配置
		userInfo: null, //用户信息    
		openId: "", //微信小程序openid
		unionId: "", //微信unionId
		token: '',
		webUrl:''
	},
	getters: {
		//全局大类型 1~4
		// globalAuthType: (state) => {
		//   const {
		//     userInfo: { role: globalAuth },
		//   } = state;
		//   return globalAuth < 3 ? 1 : globalAuth < 5 ? 2 : globalAuth < 7 ? 3 : 4;
		// },
	},
	mutations: {
		//系统配置
		SET_SYSTEM_CONFIG(state, data) {
			state.system = data;
		},
		//设置token
		SET_TOKEN: (state, token) => {
			state.token = token;
		},
		//设置用户信息
		SET_USER_INFO: (state, info) => {
			state.userInfo = info;
		},
		//退出登录
		LOG_OUT: (state) => {
			state.token = "";
			state.userInfo = {};
		},
		// 设置openid
		SET_OPENID: (state, info) => {
			state.openId = info;
		},
		// 设置unionId
		SET_UNIONID: (state, info) => {
			state.unionId = info;
		},
	},
	actions: {
		//登录
		login({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				loginApi(params)
					.then((res) => {
						resolve(res);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		//刷新token
		getAccessToken({
			commit
		}, params) {
			return new Promise((resolve, reject) => {
				getAccessToken(params)
					.then(({
						result,
						message,
						status
					}) => {
						commit("SET_TOKEN", result);
						resolve({
							message,
							status
						});
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
		//获取用户信息
		getUserInfo({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getInfo()
					.then((res) => {
						if (res.code == 200) {
							commit("SET_USER_INFO", res.user);
						}
						resolve(1);
					})
					.catch((error) => {
						reject(error);
					});
			});
		},
	},
	module: {},
	plugins: [
		createPersistedState({
			storage: {
				getItem: (key) => uni.getStorageSync(key),
				setItem: (key, val) => uni.setStorageSync(key, val),
				removeItem: (key) => uni.removeStorageSync(key),
			},
		}),
	],
});

export default store;